//
//  ActionsViewController.swift
//  Woolgathering
//
//  Created by 范东 on 2022/3/7.
//

import UIKit
import HandyJSON

class ActionsViewController: BaseViewController {
    
    lazy var searchRC : ActionSearchResultController = {
        let searchRC = ActionSearchResultController()
        searchRC.nav = navigationController as? BaseNavigationController
        return searchRC
    }()
    
    lazy var searchC : UISearchController = {
        let searchC = UISearchController(searchResultsController: searchRC)
        searchC.searchBar.delegate = searchRC
        searchC.searchResultsUpdater = searchRC
        searchC.delegate = self
        searchC.view.addSubview(searchRC.view)
        return searchC
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationItem.title = NSLocalizedString("Actions Center", comment: "")
        navigationItem.searchController = searchC
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadLocalData()
    }
    
    func loadLocalData(){
        dataArray.removeAll()
        let path = Bundle.main.path(forResource: "actions", ofType: "json") ?? ""
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path))
            let jsonObject =  try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String:Any]
            let jsonDataArray = jsonObject["data"] as! [[String:Any]]
            for dict in jsonDataArray {
                let model = ActionModel.deserialize(from: dict)
                dataArray.append(model ?? ActionModel())
            }
            searchRC.dataArray = dataArray
            collectionView.reloadData()
        } catch {
            debugPrint(error)
        }
    }
    

    var dataArray = [ActionModel]()
    
    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .systemBackground
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(ActionItemCell.classForCoder(), forCellWithReuseIdentifier: NSStringFromClass(ActionItemCell.classForCoder()))
        return collectionView
    }()
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension ActionsViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ActionItemCell.classForCoder()), for: indexPath) as! ActionItemCell
        cell.model = dataArray[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: floor((UIScreen.main.bounds.size.width - 45) / 2), height: 110)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: String(indexPath.row) as NSCopying) {() -> UIViewController? in
            return nil
        } actionProvider: { (element) -> UIMenu? in
            let addAction = UIAction(title: NSLocalizedString("add", comment: ""), image: UIImage(systemName: "plus.circle")) { action in
                let model = self.dataArray[indexPath.item]
                var array = UserDefaults.standard.array(forKey: .myActions)
                array?.append(model.toJSON())
                UserDefaults.standard.setValue(array, forKey: .myActions)
                UserDefaults.standard.synchronize()
                
                UNUserNotificationCenter.current().getNotificationSettings { setting in
                    if setting.notificationCenterSetting != .enabled{
                        self.requestAuth()
                    }
                }
            }
            return UIMenu(title:"", children: [addAction])
        }
    }
    
    func requestAuth(){
        UNUserNotificationCenter.current().requestAuthorization(options: .alert) { granted, error in
            if error != nil{
                DispatchQueue.main.async {
                    self.view.makeToast(error?.localizedDescription)
                }
            }else{
                if !granted {
                    DispatchQueue.main.async {
                        let alert = UIAlertController(title: NSLocalizedString("Tip", comment: ""), message: NSLocalizedString("We don't have your notification permission, Please fix it in set page.", comment: ""), preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
                        alert.addAction(UIAlertAction(title: NSLocalizedString("Fix", comment: ""), style: .destructive, handler: { action in
                            DispatchQueue.main.async {
                                let app = UIApplication.shared
                                let url = URL(string: UIApplication.openSettingsURLString)
                                app.open(url!, options: [:], completionHandler: nil)
                            }
                        }))
                        self.present(alert, animated: true, completion: nil)
                    }
                }
            }
        }
    }
}

extension ActionsViewController : UISearchControllerDelegate{
    
}

